// 获取画布和上下文
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');

// 游戏参数
const gridSize = 20;
const tileCount = canvas.width / gridSize;

// 蛇的属性
let snake = [];
let snakeX = 10 * gridSize;
let snakeY = 10 * gridSize;
let velocityX = 0;
let velocityY = 0;
let tailLength = 3;

// 食物的属性
let foodX = 15 * gridSize;
let foodY = 15 * gridSize;

// 游戏状态
let score = 0;
let gameRunning = false;
let gameLoopId = null;

// 获取DOM元素
const scoreElement = document.getElementById('score');
const startBtn = document.getElementById('startBtn');
const pauseBtn = document.getElementById('pauseBtn');
const resetBtn = document.getElementById('resetBtn');

// 事件监听器
startBtn.addEventListener('click', startGame);
pauseBtn.addEventListener('click', pauseGame);
resetBtn.addEventListener('click', resetGame);

document.addEventListener('keydown', changeDirection);

// 开始游戏
function startGame() {
    if (!gameRunning) {
        gameRunning = true;
        velocityX = 1;
        velocityY = 0;
        gameLoopId = setInterval(gameLoop, 100);
    }
}

// 暂停游戏
function pauseGame() {
    if (gameRunning) {
        gameRunning = false;
        clearInterval(gameLoopId);
    } else {
        gameRunning = true;
        gameLoopId = setInterval(gameLoop, 100);
    }
}

// 重置游戏
function resetGame() {
    gameRunning = false;
    clearInterval(gameLoopId);
    snake = [];
    snakeX = 10 * gridSize;
    snakeY = 10 * gridSize;
    velocityX = 0;
    velocityY = 0;
    tailLength = 3;
    score = 0;
    scoreElement.textContent = score;
    generateFood();
    drawGame();
}

// 改变方向
function changeDirection(event) {
    const keyPressed = event.keyCode;
    const LEFT = 37;
    const UP = 38;
    const RIGHT = 39;
    const DOWN = 40;

    const goingUp = (velocityY === -1);
    const goingDown = (velocityY === 1);
    const goingRight = (velocityX === 1);
    const goingLeft = (velocityX === -1);

    if (keyPressed === LEFT && !goingRight) {
        velocityX = -1;
        velocityY = 0;
    }

    if (keyPressed === UP && !goingDown) {
        velocityX = 0;
        velocityY = -1;
    }

    if (keyPressed === RIGHT && !goingLeft) {
        velocityX = 1;
        velocityY = 0;
    }

    if (keyPressed === DOWN && !goingUp) {
        velocityX = 0;
        velocityY = 1;
    }
}

// 生成食物
function generateFood() {
    foodX = Math.floor(Math.random() * tileCount) * gridSize;
    foodY = Math.floor(Math.random() * tileCount) * gridSize;

    // 确保食物不会生成在蛇身上
    for (let i = 0; i < snake.length; i++) {
        if (snake[i].x === foodX && snake[i].y === foodY) {
            generateFood();
            break;
        }
    }
}

// 游戏循环
function gameLoop() {
    // 移动蛇头
    snakeX += velocityX * gridSize;
    snakeY += velocityY * gridSize;

    // 边界碰撞检测
    if (snakeX < 0) snakeX = canvas.width - gridSize;
    if (snakeX >= canvas.width) snakeX = 0;
    if (snakeY < 0) snakeY = canvas.height - gridSize;
    if (snakeY >= canvas.height) snakeY = 0;

    // 更新蛇的位置
    let snakeHead = {
        x: snakeX,
        y: snakeY
    };

    snake.unshift(snakeHead);

    // 检查是否吃到食物
    if (snakeX === foodX && snakeY === foodY) {
        score++;
        scoreElement.textContent = score;
        tailLength++;
        generateFood();
    } else {
        // 移除尾部
        snake.pop();
    }

    // 检查是否撞到自己
    for (let i = 1; i < snake.length; i++) {
        if (snake[i].x === snakeX && snake[i].y === snakeY) {
            gameRunning = false;
            clearInterval(gameLoopId);
            alert('游戏结束! 你的得分: ' + score);
            break;
        }
    }

    // 绘制游戏
    drawGame();
}

// 绘制游戏
function drawGame() {
    // 清空画布
    ctx.fillStyle = '#eee';
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    // 绘制蛇
    ctx.fillStyle = '#4CAF50';
    for (let i = 0; i < snake.length; i++) {
        ctx.fillRect(snake[i].x, snake[i].y, gridSize - 2, gridSize - 2);
    }

    // 绘制蛇头
    ctx.fillStyle = '#2E7D32';
    ctx.fillRect(snakeX, snakeY, gridSize - 2, gridSize - 2);

    // 绘制食物
    ctx.fillStyle = '#F44336';
    ctx.fillRect(foodX, foodY, gridSize - 2, gridSize - 2);
}

// 初始化游戏
resetGame();